<?php

namespace app\logic\single;

use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;

class WechatSingle
{

    private static $inc;
    /**
     * @var array
     */
    private $config;

    private function __clone(){

    }

    public static function getInstance(){
        if(is_null(self::$inc)){
            self::$inc = new self();
        }
        return self::$inc;
    }
    private function __construct()
    {
        $config = config('wechat');
        $this->config = $config;
    }

    /**
     * 获取openid
     * @param string $code
     * @return array|\EasyWeChat\Kernel\Support\Collection|false|object|\Psr\Http\Message\ResponseInterface|string
     */
    function getOpenidByCode(string $code=''){
        $app = Factory::officialAccount($this->config);
        if(empty($code)){
            return false;
        }
        try {
            $token = $app->oauth->getAccessToken($code);
            return $app->user->get($token['openid']);

        }catch (\Exception $exception){
            return $exception->getMessage();
        }
    }
    function getBuildConfig($url=''){
        $app = Factory::officialAccount($this->config);
        if(!empty($url)){
            $app->jssdk->setUrl($url);
        }
        return $app->jssdk->buildConfig(array('updateAppMessageShareData', 'updateTimelineShareData', 'onMenuShareTimeline', 'onMenuShareAppMessage'), $debug = true, $beta = false, $json = false);
    }
}